package org.mikhaylov.cp.web.command.impl;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.mikhaylov.cp.service.command.ServiceCommandContainer;
import org.mikhaylov.cp.service.response.Response;
import org.mikhaylov.cp.service.response.ResponseType;
import org.mikhaylov.cp.web.command.WebCommand;
import org.mikhaylov.cp.web.storage.Path;

public class RegisterWebCommand extends WebCommand {

	private Logger log = Logger.getLogger(RegisterWebCommand.class);
	
	private static final long serialVersionUID = 1034789098244128889L;
	private String login = null;
	private String password = null;
	private String passwordRepeat = null;
	private String city = null;
	
	@Override
	protected boolean checkParams(HttpServletRequest request) {
		if (request.getParameter("login") == null || request.getParameter("password") == null
				|| request.getParameter("passwordRepeat") == null
				|| request.getParameter("city") == null
				|| request.getParameter("login").isEmpty()
				|| request.getParameter("password").isEmpty()
				|| request.getParameter("passwordRepeat").isEmpty()
				|| request.getParameter("city").isEmpty()) {
			forward = Path.PAGE_ERROR;
			request.setAttribute("errorMessage", "Wrong parameters");
			return false;
		}
		return true;
	}

	@Override
	protected boolean extractParams(HttpServletRequest request) {
		login = request.getParameter("login");
		password = request.getParameter("password");
		passwordRepeat = request.getParameter("passwordRepeat");
		city = request.getParameter("city");

		if (!password.equals(passwordRepeat)) {
			forward = Path.PAGE_ERROR;
			request.setAttribute("errorMessage", "Passwords do not match");
			return false;
		}
		return true;
	}

	@Override
	protected void process(HttpServletRequest request) {
		request.setAttribute("login", login);
		request.setAttribute("password", password);
		request.setAttribute("passwordRepeat", passwordRepeat);
		request.setAttribute("city", city);
		Response r = ServiceCommandContainer.get("register").execute(request, null);
		if (r.getType() == ResponseType.ERROR) {
			forward = Path.PAGE_ERROR;
			request.setAttribute("errorMessage", r.getMeta());
			log.debug(r.getMeta());
			return;
		}
		forward = Path.PAGE_PRG;
		request.setAttribute("next", Path.COMMAND_R_MENU);
		request.getSession().setAttribute("user", request.getAttribute("user"));
	}

}
